package com.example.myproject.service.impl;

import com.example.myproject.dto.rating.RatingRequest;
import com.example.myproject.dto.rating.RatingResponse;
import com.example.myproject.mapper.MarkingMapper;
import com.example.myproject.mapper.TorrentMapper;
import com.example.myproject.model.Marking;
import com.example.myproject.model.Torrent;
import com.example.myproject.security.JwtAuthenticationFilter;
import com.example.myproject.service.RatingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

@Service
public class RatingServiceImpl implements RatingService {

    @Autowired
    private MarkingMapper markingMapper;

    @Autowired
    private TorrentMapper torrentMapper;

    @Override
    @Transactional
    public RatingResponse submitRating(RatingRequest req) {
        // 获取当前用户ID（仿照点赞）
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = null;
        if (auth.getPrincipal() instanceof JwtAuthenticationFilter.UserPrincipal) {
            userId = ((JwtAuthenticationFilter.UserPrincipal) auth.getPrincipal()).getId();
        } else {
            throw new IllegalStateException("Unexpected principal type");
        }

        // 创建评分记录
        Marking marking = new Marking();
        marking.setTorrent_id(req.getTorrent_id().longValue());
        marking.setUser_id(userId);
        marking.setWeight_factor(req.getWeight_factor());
        marking.setScore(req.getRating());
        marking.setMarking_time(LocalDateTime.now());

        // 保存到数据库
        markingMapper.insert(marking);

        // 更新 torrent 表的评分统计
        updateTorrentScore(req.getTorrent_id().longValue());

        // 构建响应
        RatingResponse resp = new RatingResponse();
        resp.setMarking_id(marking.getMarrking_id().intValue());
        resp.setTorrent_id(req.getTorrent_id());
        resp.setUser_id(userId);
        // 这里如果需要用户等级，可以自行实现
        double roundedRating = Math.round(req.getRating() * 100.0) / 100.0;
        resp.setRating((double)roundedRating);
        resp.setWeighted_rating((int)(req.getRating() * req.getWeight_factor()));
        resp.setComment(req.getComment());
        resp.setRating_createtime(Instant.now().atZone(ZoneId.of("UTC")).toString());

        return resp;
    }

    private void updateTorrentScore(Long torrentId) {
        // 计算新的平均分
        Double newScore = markingMapper.calculateAverageScore(torrentId);

        // 获取当前评分计数并加1
        int  markingCount=torrentMapper.getMarkingCount(torrentId) + 1;

        // 更新 torrent 表
        Torrent torrent = torrentMapper.selectById(torrentId);
        if (torrent != null) {
            torrent.setScore(newScore);
            torrent.setMarkingCount(markingCount);

            torrentMapper.updateById(torrent);
        }
    }
}